package com.coship.acf;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;

import com.coship.acf.annotation.CacheQuery;
import com.coship.acf.annotation.CacheUpdate;

/**
 * @author 906324
 */
@Aspect
public class CacheInterceptor implements Ordered{
	protected Logger logger = LoggerFactory.getLogger(CacheInterceptor.class);
	
	@Pointcut("@annotation(com.coship.acf.annotation.CacheQuery) || " +
			  "@annotation(com.coship.acf.annotation.CacheUpdate)")  
    public void pointCut(){}
	
	@Around("pointCut()")
	public Object doCache(ProceedingJoinPoint pjp) throws Throwable {
		if (!CacheService.isCacheEnable()) {
			return pjp.proceed();
		}
		Object result = null;
		MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
		Method method = methodSignature.getMethod();
		String region = pjp.getTarget().getClass().getSimpleName();
		CacheQuery cacheTimeQuery = method.getAnnotation(CacheQuery.class);
		CacheUpdate cacheTimeUpdate = method.getAnnotation(CacheUpdate.class);
		try {
			if (cacheTimeQuery != null) {
				result = query(region, method.getName(), pjp.getArgs(), cacheTimeQuery.value(), cacheTimeQuery.user(), pjp);
			} else if (cacheTimeUpdate != null) {
				pjp.proceed();
				update(region, pjp.getArgs(),cacheTimeUpdate.value(),cacheTimeUpdate.user());
			} else {
				result = pjp.proceed();
			}
		} catch (Exception e) {
			logger.error("缓存异常", e);
		}
		return result;
	}
	
	/**
	 *  查询时先查询缓存和缓存更新时间，对比缓存查询时间和更新时间
	 *  如果缓存为空或者过期，则查询数据库，然后把查询结果和查询时间放入缓存
	 */
	private Object query(String region, String method, Object[] args,String timeKeyValue, boolean user, 
			ProceedingJoinPoint pjp) throws Throwable {
		String queryKey = getQueryKey(region, method, args);
		String timeKey = getTimeKey(region, args, timeKeyValue, user);
		if(StringUtils.isBlank(timeKeyValue) && CacheService.getUser() == null){
			CacheService.log("无timeKey条件，直接查询数据库");
			return pjp.proceed();
		}
		List<Object> values = CacheService.mget(queryKey, timeKey);
		Object value = values.get(0);
		Object time = values.get(1);
		String log = "";
		if (value == null) {
			log = "缓存查询为空，查询数据库，设置缓存";
			value = pjp.proceed();
			CacheService.set(queryKey, new CacheObject(value));
		} else {
			log = "缓存查询到数据";
			CacheObject cacheObject = (CacheObject) value;
			value = cacheObject.getValue();
			if (time != null && cacheObject.getTime() < Long.parseLong(time.toString())) {
				log += ",但是过期，查询数据库，设置缓存";
				value = pjp.proceed();
				CacheService.set(queryKey, new CacheObject(value));
			} 
		}
		CacheService.log(log+"."+queryKey);
		return value;
	}
	
	/**
	 * 数据更新会根据时间表达式，更新对应的缓存更新时间
	 */
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private void update(String region,Object[] args ,String[] timeKeyValues, boolean user) throws Throwable{
		if(timeKeyValues.length == 0 && CacheService.getUser() == null){
			return;
		}
		timeKeyValues = timeKeyValues.length == 0 ? new String[]{""} : timeKeyValues;
		Set<String> timeKeys = new HashSet<String>();
		for (String timeKeyValue : timeKeyValues) {			
			String timeKey = getTimeKey(region, args, timeKeyValue, user);
			timeKeys.add(timeKey);
		}
		List<Object> times = new ArrayList<Object>();
		long time = System.currentTimeMillis();
		for(String timeKey : timeKeys){			
			times.add(timeKey);
			times.add(time);
			CacheService.log("数据更新，time=" + sdf.format(new Date(time)));
		}
		CacheService.mset(times);
	}
	
	/**
	 * 查询缓存key是：类名+方法名+参数
	 */
	public static String getQueryKey(String region,String method,Object[] args){
		Object[] theArgs = new Object[args.length];
		for (int i = 0; i < args.length; i++) {
			theArgs[i] = args[i] == null ? "NULL" : args[i];
		}
		String queryKey = "query_" + region + "." + method + "("
				+ StringUtils.join(theArgs, ",") + ")";
		return queryKey;
	}
	
	/**
	 * 缓存更新时间缓存key是:类名+表达式+用户名
	 */
	public static String getTimeKey(String region, Object[] args, String timeKeyValue, boolean user) throws Exception{
		String timeKey = "time_" + region;
		if (!StringUtils.isBlank(timeKeyValue)) {
			String[] values = timeKeyValue.split(",");
			for (String value : values) {
				String[] valueItem = value.split("=");
				String[] argValue = valueItem[1].split("\\.");
				Object arg = args[Integer.parseInt(argValue[0]) - 1];
				if(arg == null){
					continue;
				}
				if (argValue.length == 2) {
					arg = PropertyUtils.getProperty(arg, argValue[1]);
					if(arg == null){
						continue;
					}
				}
				timeKey += "|" + valueItem[0] + "=" + arg;
			}
		}
		timeKey += user && CacheService.getUser() != null ? ("|user=" + CacheService.getUser()) : "";
		return timeKey;
	}

	@Override
	public int getOrder() {
		return 0;
	}
}